#!/bin/gawk -f
#
# script to convert AQUA torsion angle restraint file to XPLOR format
# Ton Rullmann, Oct. 21, 1997
# Mia Raves and Jurgen Doreleijers, Thu Jun 18 18:38:14 WDT 1998

function abs(Argument) {
    if (Argument<0) {
	     Argument = -Argument
    }
    return(Argument)
}

function to_0_360(Argument) {
# transforms the argument to the range [0, 360>
    while ( Argument >= 360 ) {
	Argument -= 360
    }
    while ( Argument < 0 ) {
	Argument += 360
    }
    return(Argument)    
}

function to_180 ( Argument ) {
# transforms the argument to the range <-180, 180]
    while ( Argument > 180 ) {
	Argument -= 360
    }
    while ( Argument <= -180 ) {
	Argument += 360
    }
    return(Argument)    
}

function average_angles ( alpha, beta ) {
# Angles should be in range [0-360>
# Resulting average is also in this range

    average = (alpha+beta)/2
    if ( alpha <= beta ) {
	average += 180
    } 
    
    average = to_0_360( average )
    
    return(average)    
}

function difference_angles ( alpha, beta ) {
# Angles should be in range [0-360>
# Resulting difference is in the range [0, 180]

    if ( alpha <= beta ) {
	deviation =  beta - alpha
    } else {
	deviation =  alpha - beta
    }
    
    if ( deviation > 180 ) {
	deviation = 360 - deviation
    }

    if (( deviation < 0 ) || (deviation > 180)) {
        print "impossible deviation calculated for angles" > "/dev/tty"
        print alpha,  " and ", beta > "/dev/tty"
	exit (1)
    }
    
    return(deviation)    
}

BEGIN {
    force_cnst = 1
    force_exp = 2
}

/CHAIN/ { 
    print "chain/segid not implemented" > "/dev/tty"
    exit (1)
}

/ANGLE/ {
    if ( $4 == "PHI" ) {
	printf( "assign ( resid %4i and name c )   (resid %4i and name n )\n", $3-1,$3 )
	printf( "       ( resid %4i and name ca)   (resid %4i and name c   )  ", $3,  $3 )
    }
    else if ( $4 == "PSI" ) {
	printf( "assign ( resid %4i and name n )   (resid %4i and name ca)\n", $3, $3 )
	printf( "       ( resid %4i and name c )   (resid %4i and name n   )  ", $3, $3+1 )
    }
    else if ( $4 == "CHI1" ) {
	at = "cg"
	if ( $2 ~ /^CYS/ ) at = "sg"
	else if ( $2 ~ /^ILE/ ) at = "cg1"
	else if ( $2 ~ /^SER/ ) at = "og"
	else if ( $2 ~ /^THR/ ) at = "og1"
	else if ( $2 ~ /^VAL/ ) at = "cg1"
	else if ( $2 ~ /^UNK/ ) {
	    print "can't translate:", $0 > "/dev/tty"
	    next
	}
	printf( "assign ( resid %4i and name n )   (resid %4i and name ca)\n", $3, $3 )
	printf( "       ( resid %4i and name cb)   (resid %4i and name %-3s )  ", $3, $3, at )
    }
    else {
	print "can't translate:", $0 > "/dev/tty"
	next
    }

    up = to_0_360( $5 )
    low = to_0_360( $6 )
        
    average = average_angles( up, low)
    
    deviation = difference_angles( average, low )

    average = to_180( average )    
    
    printf( "%7.2f %7.2f %7.2f %i\n", force_cnst, average, deviation, force_exp )
}
